package cn.doitedu.javase;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;

import java.io.*;

public class Things2Bytes {

    public void testFile2String() throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("cn/doitedu/javase/schema.conf")));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line=br.readLine())!=null){
            sb.append(line);
        }

        String s = sb.toString();

        ZooKeeper zk = new ZooKeeper("", 2000, null);
        zk.create("/conf",s.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }



    @Test
    public void object2Bytes() throws Exception {


        Person p = new Person();
        p.setAge(18);
        p.setName("马小婷");
        p.setSalary(18000);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oout = new ObjectOutputStream(bout);

        oout.writeObject(p);


        byte[] bytes = bout.toByteArray();
        ZooKeeper zk = new ZooKeeper("spark01:2181,spark02:2181,spark03:2181", 2000, null);
        zk.create("/person",bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);


        //  从zk中取出字节，反序列化成person对象
        byte[] data = zk.getData("/person", false, null);
        ByteArrayInputStream bin = new ByteArrayInputStream(data);
        ObjectInputStream oin = new ObjectInputStream(bin);
        Person o = (Person) oin.readObject();

        System.out.println(o.getName());
        System.out.println(o.getAge());
        System.out.println(o.getSalary());


    }
}
